/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.DeviceService;
import com.lmx.persistence.service.EmployeeService;
import com.lmx.persistence.service.NursingService;
import com.lmx.persistence.service.UserService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Device;
import com.lmx.repoDomain.tmodel.Employee;

@JsonApiResourceRepository(Employee.class)
@Component
public class EmployeeRepository extends BaseRepository<Employee> {

	@Autowired
	private UserService userService;

	@Autowired
	private NursingService nursingService;
	@Autowired
	private EmployeeService<Employee> employeeSrv;
	@Autowired
	DeviceService<Device> deviceSrv;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(Employee.class);
	}

	@Override
	@JsonApiFindAll
	public Iterable<Employee> findAll(final QueryParams requestParams) {
		Map<String, String> keyMap = CommonUtil
				.getKeyMapByFilter(requestParams);
		if (keyMap.containsKey("forTenant")
				&& CommonConstants.DEFAULT_STATUS_YES_1.toString().equals(
						keyMap.get("forTenant"))) {
			Long tenantId = ActionContextHolder.getContext().getTenantId();
			return employeeSrv.findByTenant(tenantId);
		}
		String queryType = keyMap.get("queryType");
		if ("employeeWithoutGroup".equals(queryType)) {
			return nursingService.getEmployeeListFilterGroup();
		} else {
			return super.findAll(requestParams);
		}
	}

	@Override
	@JsonApiSave
	public Employee save(Employee employee) {
		if (employee.getId() == null) {
			List<Employee> temp = userService.getEmployeeByCardCode(employee
					.getStaffCardCode());
			if (temp == null || temp.size() == 0) {
				employee = employeeSrv.create(employee);
			} else {
				employee.setErrcode(3);// 身份证
				throw new BusinessException(null,
						CommonConstants.ERROR_CODE.CARDCODE_ERROR.label(), null);
			}
		} else {
			Employee oldData = userService.getEmployeeById(employee.getId());
			if (employee.getDelStatus() == 1) {// 删除
				if (oldData.getStaffStatus().getTypecode()
						.equals(ICommonConstants.STAFFSTATUS.LEAVE.lable())) {
					BeanUtils.copyProperties(oldData, employee, "delStatus");
					employeeSrv.delete(employee);
				} else {
					throw new BusinessException(null,
							CommonConstants.ERROR.EMPLOYEE_SAVE_NOT_LEAVE
									.label(), "未离职员工不能删除");
				}

			} else {
				Boolean isLeaveChange = (oldData.getStaffStatus() != null && oldData
						.getStaffStatus().getTypecode()
						.equals(ICommonConstants.STAFFSTATUS.IN.lable()))
						&& (employee.getStaffStatus() != null && employee
								.getStaffStatus()
								.getTypecode()
								.equals(ICommonConstants.STAFFSTATUS.LEAVE
										.lable()));
				if (isLeaveChange) {
					if (!employeeSrv.checkDimissionStatus(oldData, employee)) {// 离职
						throw new BusinessException(null,
								CommonConstants.ERROR.EMPLOYEE_SAVE_INGROUP
										.label(), "员工属于护工组/有未完成排班,不能离职");
					}
					if (!employeeSrv.checkLeaderAndDevice(employee)) {// 离职
						throw new BusinessException(null,
								CommonConstants.ERROR.EMPLOYEE_NOT_LEAVE
										.label(), "请先进行部门领导工作交接");
					}
					employeeSrv.leaveEmployee(employee);// 员工离职
				} else {
					List<Employee> temp = userService
							.getEmployeeByCardCodeFilterId(
									employee.getStaffCardCode(),
									employee.getId());
					if (temp != null && temp.size() > 0) {
						employee.setErrcode(3);// 身份证重复
						throw new BusinessException(null,
								CommonConstants.ERROR_CODE.CARDCODE_ERROR
										.label(), null);
					}
					this.deviceSrv.updateStatus(employee, oldData);// 无论修改与否先将old置为空闲再将新的置为占用
					dslJpaService.update(employee);
				}
			}
		}
		return employee;
	}

}
